package tjs.study.notes.dotest.jvm.classload.agent;

import tjs.study.notes.dotest.TjsStudyNotesApplication;
import tjs.study.notes.dotest.jvm.classload.DoTestOfMyClassLoad;
import tjs.study.notes.dotest.jvm.classload.OtherPackagerClassLoader;

/**
 * Created by Nicky.Tang on 2024/7/17 16:33
 *
 * @since 02.12.10
 */
public class DoTest {
    public static void main(String[] args) throws Exception{
        OtherPackagerClassLoader noParentsClassLoader = new OtherPackagerClassLoader(TjsStudyNotesApplication.work_space_pre + "/target/classes/");
        Class<?> userClassOther = Class.forName("tjs.study.notes.dotest.jvm.classload.agent.KafkaPlugin", true, noParentsClassLoader);
        Class<?> userClassApp = Class.forName("tjs.study.notes.dotest.jvm.classload.agent.KafkaPlugin", true, Thread.currentThread().getContextClassLoader());
        System.out.println(userClassOther == userClassApp);//false 调用main方法前，DoTestOfMyClassLoad实际上默认已由AppClassLoader加载过了
        try {
            KafkaPlugin objectApp = (KafkaPlugin) userClassApp.getConstructor().newInstance();
            // userClassOther这个对象的类加载器为'noParentsClassLoader'，与DoTestOfMyClassLoad的'AppClassLoader'不一致，所以无法强制转换
            KafkaPlugin objectOther = (KafkaPlugin) userClassOther.getConstructor().newInstance();
        } catch (ClassCastException ex) {
            ex.printStackTrace();//Exception in thread "main" java.lang.ClassCastException: tjs.study.notes.dotest.jvm.classload.DoTestOfMyClassLoad cannot be cast to tjs.study.notes.dotest.jvm.classload.DoTestOfMyClassLoad
        }
        
        // IPlugin在'noParentsClassLoader'中，会强制由父加载器'AppClassLoader'加载
        IPlugin object = (IPlugin) userClassOther.getConstructor().newInstance();
        object.start();// kafka采集中。。。
    }
}
